package dao

import (
	"fmt"
	"laohuo/model"
)

func FetchWarehouseBill(page, pagesize uint) ([]*model.Warehousebill, error) {
	db, err := connect()
	if err != nil {
		return nil, err
	}
	defer db.Close()

	rows, err := db.Query("SELECT * FROM `warehouse_bill` WHERE isdel=0 ORDER BY `time` DESC LIMIT ?,?", (page-1)*pagesize, pagesize)
	if err != nil {
		return nil, fmt.Errorf("查询失败: %v", err)
	}
	defer rows.Close()

	var whs []*model.Warehousebill
	for rows.Next() {
		var wh model.Warehousebill
		var isdel uint8
		if err := rows.Scan(&wh.Id, &wh.WarehouseId, &wh.SKUID, &wh.Num, &wh.Type, &wh.Note, &wh.Feedback, &wh.User, &wh.Time, &wh.Sign, &isdel); err != nil {
			continue
		}
		whs = append(whs, &wh)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("数据解析失败: %v", err)
	}
	return whs, nil
}

func FetchWarehouseBillWithSku(page, pagesize uint) ([]*model.WarehousebillDetail, error) {
	db, err := connect()
	if err != nil {
		return nil, err
	}
	defer db.Close()

	rows, err := db.Query("SELECT * FROM `warehouse_bill` WHERE isdel=0 ORDER BY `time` DESC LIMIT ?,?", (page-1)*pagesize, pagesize)
	if err != nil {
		return nil, fmt.Errorf("查询失败: %v", err)
	}
	defer rows.Close()

	var whs []*model.Warehousebill
	var whd []*model.WarehousebillDetail
	var skuids []uint
	for rows.Next() {
		var wh model.Warehousebill
		var isdel uint8
		if err := rows.Scan(&wh.Id, &wh.WarehouseId, &wh.SKUID, &wh.Num, &wh.Type, &wh.Note, &wh.Feedback, &wh.User, &wh.Time, &wh.Sign, &isdel); err != nil {
			continue
		}
		whs = append(whs, &wh)
		skuids = append(skuids, wh.SKUID)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("数据解析失败: %v", err)
	}
	if len(whs) == 0 {
		return whd, nil
	}

	var skumap = make(map[uint]*model.SKU, len(skuids))
	skus, err := FetchBatchSkuById(skuids)
	if err != nil {
		return whd, err
	}
	for _, s := range skus {
		skumap[s.Id] = s
	}
	for _, w := range whs {
		whd = append(whd, &model.WarehousebillDetail{
			Warehousebill: w,
			SKU:           skumap[w.SKUID],
		})
	}

	return whd, nil
}

func CountWarehouseBill() (int, error) {
	db, err := connect()
	if err != nil {
		return 0, err
	}
	defer db.Close()

	var total int
	if err := db.QueryRow("SELECT COUNT(*) FROM `warehouse_bill` WHERE `isdel`=0").Scan(&total); err != nil {
		return 0, err
	}
	return total, nil
}
